<?php

namespace Tasker\Configurator;

/**
 * Description of ServiceFactories
 * @property-read ModelsLocator $models
 * @author Jan Voracek
 */
class ServiceFactories
{

	public static function createServiceConnection(\Nette\DI\IContainer $container)
	{
		$db = $container->params['database'];
		$pdo = new \PDO("{$db['driver']}:host={$db['host']};dbname={$db['database']}", $db['user'], $db['pass']);
		if (isset($db['charset']))
		{
			$pdo->exec("SET CHARACTER SET " . $db['charset']);
		}
		$notOrmCacheDir = $container->params['tempDir'] . '/cache/NotORM';
		$notOrmCache = new \NotORM_Cache_File($notOrmCacheDir . '/cache');
		
		$notORM = new \NotORM($pdo, new TaskerDbStructure()/*,$notOrmCache*/);
		
		if ($db['profiler'])
		{
			$panel = \Tasker\Debug\NotOrmPanel::getInstance($notORM);
			\Nette\Diagnostics\Debugger::addPanel($panel);
		}
		return $notORM;
	}

	public static function createServiceModels(\Nette\DI\IContainer $container)
	{
		$models = new ModelsLocator($container);
		return $models;
	}

}

class TaskerDbStructure extends \NotORM_Structure_Convention
{

	public function __construct()
	{
		parent::__construct($primary = 'id', $foreign = '%s_id', $table = '%s');
	}

	public function getReferencedTable($name, $table)
	{
		if ($table === 'prerequisite_task' && $name === 'prerequisite')
		{
			$name = 'task';
		}
		if ($table === 'task' && ($name === 'creator' || $name === 'worker'))
		{
			$name = 'user';
		}
		return parent::getReferencedTable($name, $table);
	}

}
